<template>
  <up-picker
    :show="show"
    ref="uPickerRef"
    :loading="loading"
    :columns="columns"
    keyName="name"
    :defaultIndex="[0, 0]"
    @change="changeHandler"
    @cancel="show = false"
    @confirm="handleConfirm"
  ></up-picker>
</template>

<script setup>
import { ref, reactive, watch } from "vue";
import { apiConfigAddress } from "@/common/apis/common.js";

const emits = defineEmits(["confirm"]);

const show = defineModel({ type: Boolean, default: false });

const loading = ref(false);

const columns = reactive([[], []]);

const uPickerRef = ref(null);

watch(show, async (val) => {
  if (val) {
    const response = await fetchAddressData();
    columns[0] = response;
    const response2 = await fetchAddressData(response[0].id);
    columns[1] = response2;
    uPickerRef.value.setIndexs([0, 0]);
  }
});

async function fetchAddressData(parent_id = undefined) {
  const response = await apiConfigAddress({ parent_id });
  if (response) {
    return response;
  }
}

const changeHandler = async (e) => {
  const { columnIndex, index, value } = e;
  const current = value[columnIndex];
  console.log(current);
  if (columnIndex === 0) {
    if (current.children && current.children.length) {
      uPickerRef.value.setColumnValues(1, current.children);
    } else {
      loading.value = true;
      const response = await fetchAddressData(current.id);
      uPickerRef.value.setColumnValues(1, response);
      loading.value = false;
    }
  }
};

function handleConfirm(e) {
  emits(
    "confirm",
    e.value.map((i) => i.id)
  );
}
</script>
